package cn.ffcs.util;


import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Hibernate;

import cn.ffcs.organ.model.Organization;
import cn.ffcs.product.model.Product;
import cn.ffcs.sort.model.ProductSort;
import cn.ffcs.util.context.ApplicationContextUtil;
/**
 * 
 * 字典类型DAO实现<br/> <table>
 * <tr>
 * <td>负责人/principal: </td>
 * <td colspan="2">liuzhh</td>
 * <tr>
 * <td>修改记录/revision:</td>
 * <td colspan="2"></td>
 * </tr>
 * <tr>
 * <td>日期:</td>
 * <td>修改人:</td>
 * <td>修改说明:</td>
 * </tr>
 * <tr>
 * <td></td>
 * <td></td>
 * <td></td>
 * </tr>
 * </table>
 * @author g.huangjx
 * @version $Id$
 */
public class MyList {

    /**
     * 产品类型树
     * @return
     */
    public static String getProductSortTree(List ls,String type,String module){
        StringBuffer xml=new StringBuffer();
        HttpServletRequest request =  ApplicationContextUtil.getHttpServletRequest();
        String ctx=request.getContextPath();
        xml.append("<?xml  version=\"1.0\" encoding=\"GB2312\"?>\n");
        xml.append("<TreeNode>\n");
        Iterator it =ls.iterator();
        if(type!=null&&!type.equals("")&&!type.equals("null")){
            while(it.hasNext()){
                ProductSort p=(ProductSort)it.next();
                if(p.getId()==0){
                    continue;
                }
                if(p.getChildCount()==0){
                    xml.append("<TreeNode  myId='"+p.getId()+"' text='" + p.getName()+"' "+type+"='true'></TreeNode>\n");
                }else{
                    xml.append("<TreeNode  myId='"+p.getId()+"' text='" + p.getName() +"' src='"+ctx+"/business/catalog/treeProductSort.action?conds.parentSort="+p.getId()+"&amp;conds.sortType="+p.getSortType()+"&amp;date="+System.currentTimeMillis()+"&amp;type="+type+"' "+type+"='true'></TreeNode>\n");
    
                }
                
            }
        }else{
            while(it.hasNext()){
                ProductSort p=(ProductSort)it.next();
                if(p.getId()==0){
                    continue;
                }
                if(p.getChildCount()==0){
                    if(module!=null&&!module.equals("")){
                        xml.append("<TreeNode myFun='myFunction' myId='"+p.getId()+"' text='" + p.getName()+ "' action='javascript:checkProduct("+p.getId()+")'></TreeNode>\n");
                    }else{
                        xml.append("<TreeNode myId='"+p.getId()+"' text='" + p.getName()+ "' action='javascript:checkProduct("+p.getId()+")'></TreeNode>\n");
                    }
                }else{
                    xml.append("<TreeNode myFun='myFunction' myId='"+p.getId()+"' text='" + p.getName()+ "' action='javascript:checkProduct("+p.getId()+")' src='"+ctx+"/business/catalog/treeProductSort.action?conds.parentSort="+p.getId()+"&amp;conds.sortType="+p.getSortType()+"&amp;date="+System.currentTimeMillis()+"&amp;type="+type+"&amp;module="+module+"'></TreeNode>\n");
    
                }
                
            }
        }
        xml.append("</TreeNode>\n");
        //System.out.println(xml.toString());
        return xml.toString();
    }
    /**
     * 产品树
     * @return
     */
    public static String getProductTree(List ls,String type){
    	HttpServletRequest request =  ApplicationContextUtil.getHttpServletRequest();
        String ctx=request.getContextPath();
        StringBuffer xml=new StringBuffer();
        xml.append("<?xml  version=\"1.0\" encoding=\"GB2312\"?>\n");
        xml.append("<TreeNode>\n");
        Iterator it =ls.iterator();
        if(type!=null&&!type.equals("")&&!type.equals("null")){
            while(it.hasNext()){
                Product p=(Product)it.next();
                if(p.getId()==0){
                    continue;
                }
                if(p.getChildCount()==0){
                    xml.append("<TreeNode  myId='"+p.getId()+"' text='" + p.getName()+"' "+type+"='true'></TreeNode>\n");
                }else{
                    xml.append("<TreeNode  myId='"+p.getId()+"' text='" + p.getName() +"' src="+ctx+"'/business/product/treeProduct.action?conds.pproduct="+p.getId()+"&amp;date="+System.currentTimeMillis()+"&amp;type="+type+"' "+type+"='true'></TreeNode>\n");
    
                }
                
            }
        }else{
            while(it.hasNext()){
                ProductSort p=(ProductSort)it.next();
                if(p.getId()==0){
                    continue;
                }
                if(p.getChildCount()==0){
                    xml.append("<TreeNode myId='"+p.getId()+"' text='" + p.getName()+ "'></TreeNode>\n");
                }else{
                    xml.append("<TreeNode myId='"+p.getId()+"' text='" + p.getName() + "' src='"+ctx+"/business/product/treeProduct.action?conds.pproduct="+p.getId()+"&amp;date="+System.currentTimeMillis()+"&amp;type="+type+"'></TreeNode>\n");
    
                }
                
            }
        }
        xml.append("</TreeNode>\n");
//        System.out.println(xml.toString());
        return xml.toString();
    }
    /**
     * 组织结构树
     * @return
     */
    public static String getOrganTree(List ls,String type,String module){
        StringBuffer xml=new StringBuffer();
        xml.append("<?xml  version=\"1.0\" encoding=\"GB2312\"?>\n");
        xml.append("<TreeNode>\n");
        Iterator it =ls.iterator();
        if(type!=null&&!type.equals("")&&!type.equals("null")){
            while(it.hasNext()){
                Organization p=(Organization)it.next();
                if(p.getId()==0){
                    continue;
                }
                if(p.getChildCount()==0){
                    xml.append("<TreeNode  myId='"+p.getId()+"' text='" + p.getName()+"' "+type+"='true'></TreeNode>\n");
                }else{
                    xml.append("<TreeNode  myId='"+p.getId()+"' text='" + p.getName() +"' src='treeOrgan.action?conds.superior="+p.getId()+"&amp;date="+System.currentTimeMillis()+"&amp;type="+type+"' "+type+"='true'></TreeNode>\n");
                }
                
            }
        }else{
            while(it.hasNext()){
                Organization p=(Organization)it.next();
                if(p.getId()==0){
                    continue;
                }
                if(p.getChildCount()==0){
                    if(module!=null&&!module.equals("")){
                        xml.append("<TreeNode myFun='myFunction' myId='"+p.getId()+"' text='" + p.getName()+ "'></TreeNode>\n");
                    }else{
                        xml.append("<TreeNode myId='"+p.getId()+"' text='" + p.getName()+ "'></TreeNode>\n");
                    }
                }else{
                    if(module!=null&&!module.equals("")){
                        xml.append("<TreeNode myFun='myFunction' myId='"+p.getId()+"' text='" + p.getName() + "' src='treeOrgan.action?conds.superior="+p.getId()+"&amp;date="+System.currentTimeMillis()+"&amp;type="+type+"&amp;module="+module+"'></TreeNode>\n");
                    }else{
                        xml.append("<TreeNode  myId='"+p.getId()+"' text='" + p.getName() + "' src='treeOrgan.action?conds.superior="+p.getId()+"&amp;date="+System.currentTimeMillis()+"&amp;type="+type+"'></TreeNode>\n");
                    }
                }
                
            }
        }
        xml.append("</TreeNode>\n");
//        System.out.println(xml.toString());
        return xml.toString();
    }
    /*
     * 把List转换为XML输出,不带分页信息
     */
    /*
     * 把domain转换为XML输出
     */
    public static String getStr(String str) {
        if (str == null)
            return "";
        StringBuffer xml = new StringBuffer();
        xml.append("<?xml  version=\"1.0\" encoding=\"GB2312\"?>\n");
        xml.append("<str>");
        xml.append(str);
        xml.append("</str>\n");
        return xml.toString();
    }

    public static String getAll(List ls) {
        if (ls == null)
            return "";
        StringBuffer xml = new StringBuffer();
        xml.append("<?xml  version=\"1.0\" encoding=\"GB2312\"?>\n");
        xml.append("<root>\n");
        xml.append(getContent(ls));
        xml.append("</root>\n");
        return xml.toString();
    }

    /*
     * 把domain转换为XML输出
     */
    public static String getBean(Object obj) {
        if (obj == null)
            return "";
        StringBuffer xml = new StringBuffer();
        xml.append("<?xml  version=\"1.0\" encoding=\"GB2312\"?>\n");
        xml.append("<root>\n");
        xml.append(getItem(obj));
        xml.append("</root>\n");
        return xml.toString();
    }
    /*
     * 把List转换为XML输出,带分页信息
     */
    public static String getAll(List ls,int[] str){
        return getAll(ls,str[0]+","+str[1]+","+str[2]);
    }
    /*
     * 把List转换为XML输出,带分页信息
     */
    public static String getAll(List ls, String pageInfo) {
        if (ls == null)
            return "";
        StringBuffer xml = new StringBuffer();
        xml.append("<?xml  version=\"1.0\" encoding=\"GB2312\"?>\n");
        xml.append("<root>\n");
        xml.append(getContent(ls));
        xml.append("<pageInfo>" + pageInfo + "</pageInfo>\n");
        xml.append("</root>\n");
        return xml.toString();
    }

    /*
     * 把List转换为XML输出
     */
    public static String getTokens(List ls) {
        if (ls == null)
            return "";
        StringBuffer xml = new StringBuffer();
        xml.append("<?xml  version=\"1.0\" encoding=\"GB2312\"?>\n");
        xml.append("<root>\n");
        for (int i = 0; i < ls.size(); i++) {
            xml.append("<String><id><![CDATA[").append(ls.get(i)).append(
                    "]]></id></String>");
        }
        xml.append("</root>\n");
        return xml.toString();
    }

    /*
     * XML转换
     */
    public static StringBuffer getContent(List ls) {
        StringBuffer xml = new StringBuffer();
        for (int i = 0; i < ls.size(); i++) {
            xml.append(getItem(ls.get(i)));
        }
        return xml;
    }

    /*
     * 把List转换为XML输出,支持bean list属性继续转换，也可扩展domain bean 属性再次转换
     */
    public static StringBuffer getItem(Object obj) {
        StringBuffer xml = new StringBuffer();
        // xml.append("<?xml version=\"1.0\" encoding=\"GB2312\"?>\n");
        String item = obj.getClass().getName().substring(
                obj.getClass().getName().lastIndexOf(".") + 1);
        xml.append("<" + item + ">\n");
        for (int i = 0; i < obj.getClass().getDeclaredFields().length; i++) {
            String fields = obj.getClass().getDeclaredFields()[i].getName();
            /**
             * huangchm 2009-2-8修改
             * 如果该字段是static 字段，则不加到xml当中
             */
            if(Modifier.isStatic(obj.getClass().getDeclaredFields()[i].getModifiers())){
                continue;
            }
            String result = "";
            String temp_fields = Character.toUpperCase(fields.charAt(0))
                    + fields.substring(1); // get函数后面的字符串
            String nname = "get" + temp_fields;
            Class[] types = new Class[] {};
            try {
                Method meth = obj.getClass().getMethod(nname, types);
                if (meth.invoke(obj, new Object[0]) != null) {
                    if (!meth.invoke(obj, new Object[0]).getClass().getName()
                            .equals("org.hibernate.collection.PersistentSet")) {
                        result = meth.invoke(obj, new Object[0]).toString(); // 绑定对象执行get函数
                        xml.append("<" + fields + "><![CDATA[" + result
                                + "]]></" + fields + ">\n");
                    } else {

                        Set set = (Set) meth.invoke(obj, new Object[0]);
                        if (Hibernate.isInitialized(set)) {// 判断对象是否被hibernate初化
                            xml.append("<" + fields + ">\n");
                            Iterator it = set.iterator();
                            while (it.hasNext()) {
                                Object myobj = it.next();
                                xml.append(getItem(myobj));
                            }
                            xml.append("</" + fields + ">\n");
                        }
                        // xml.append("<![CDATA["
                        // + fenYe.getFenYeAjax(fenYe.getJsp(),
                        // fenYe.getScriptName())
                        // + "]]>\n");
                    }
                }
            } catch (Exception e) {
                //log.error(转换XML错误, e);
                System.out.println("转换XML错误");
            }

        }
        /*Class superObj=obj.getClass().getSuperclass();
        for (int i = 0; i < superObj.getClass().getDeclaredFields().length; i++) {
            String fields = superObj.getClass().getDeclaredFields()[i].getName();
            System.out.println(fields);
            *//**
             * huangchm 2009-2-8修改
             * 如果该字段是static 字段，则不加到xml当中
             *//*
            if(Modifier.isStatic(superObj.getClass().getDeclaredFields()[i].getModifiers())){
                continue;
            }
            String result = "";
            String temp_fields = Character.toUpperCase(fields.charAt(0))
                    + fields.substring(1); // get函数后面的字符串
            String nname = "get" + temp_fields;
            System.out.println(nname);
            Class[] types = new Class[] {};
            try {
                Method meth = superObj.getClass().getMethod(nname, types);
                if (meth.invoke(superObj, new Object[0]) != null) {
                    if (!meth.invoke(superObj, new Object[0]).getClass().getName()
                            .equals("org.hibernate.collection.PersistentSet")) {
                        result = meth.invoke(superObj, new Object[0]).toString(); // 绑定对象执行get函数
                        xml.append("<" + fields + "><![CDATA[" + result
                                + "]]></" + fields + ">\n");
                    } else {

                        Set set = (Set) meth.invoke(superObj, new Object[0]);
                        if (Hibernate.isInitialized(set)) {// 判断对象是否被hibernate初化
                            xml.append("<" + fields + ">\n");
                            Iterator it = set.iterator();
                            while (it.hasNext()) {
                                Object mysuperObj = it.next();
                                xml.append(getItem(mysuperObj));
                            }
                            xml.append("</" + fields + ">\n");
                        }
                        // xml.append("<![CDATA["
                        // + fenYe.getFenYeAjax(fenYe.getJsp(),
                        // fenYe.getScriptName())
                        // + "]]>\n");
                    }
                }
            } catch (Exception e) {
                //log.error(转换XML错误, e);
                e.printStackTrace();
                //System.out.println("转换XML错误");
            }

        }*/
        xml.append("</" + item + ">\n");
        return xml;
    }
    public static void toChina(Object obj, String Code) {
        for (int i = 0; i < obj.getClass().getDeclaredFields().length; i++) {
            String fields = obj.getClass().getDeclaredFields()[i].getName();
            if(Modifier.isStatic(obj.getClass().getDeclaredFields()[i].getModifiers())){
                continue;
            }
            String result = "";
            String temp_fields = Character.toUpperCase(fields.charAt(0))
                    + fields.substring(1); // get函数后面的字符串
            String getName = "get" + temp_fields;
            String setName = "set" + temp_fields;
            Class[] types = new Class[] {};
            try {
                Method getMeth = obj.getClass().getMethod(getName, types);
                if (getMeth.invoke(obj, new Object[0]) != null) {
                    if (getMeth.invoke(obj, new Object[0]).getClass()
                            .isInstance(new String())) {
                        result = getMeth.invoke(obj, new Object[0]).toString(); // 绑定对象执行get函数
                        if (result == null)
                            return;
                        Class[] types2 = new Class[] { (new String())
                                .getClass() };// String 参数
                        Method setMeth = obj.getClass().getMethod(setName,
                                types2);
                        // setMeth.invoke(obj,
                        // new Object[] { new String(new String(result
                        // .getBytes("iso-8859-1"), "gbk")) }); // 绑定对象执行SET函数
                        setMeth.invoke(obj, new Object[] { new String(result
                                .getBytes("iso8859-1"), Code) }); // 绑定对象执行SET函数
                    }
                }
            } catch (Exception e) {
                System.out.println("编码转换错误");;
            }
        }
    }

    /*
     * 把一个对象的所有String 属性转化为GBK字符集
     */
    public static void toChinaPost(Object obj) {
        for (int i = 0; i < obj.getClass().getDeclaredFields().length; i++) {
            String fields = obj.getClass().getDeclaredFields()[i].getName();
            if(Modifier.isStatic(obj.getClass().getDeclaredFields()[i].getModifiers())){
                continue;
            }
            String result = "";
            String temp_fields = Character.toUpperCase(fields.charAt(0))
                    + fields.substring(1); // get函数后面的字符串
            String getName = "get" + temp_fields;
            String setName = "set" + temp_fields;
            Class[] types = new Class[] {};
            try {
                Method getMeth = obj.getClass().getMethod(getName, types);
                if (getMeth.invoke(obj, new Object[0]) != null) {
                    if (getMeth.invoke(obj, new Object[0]).getClass()
                            .isInstance(new String())) {
                        result = getMeth.invoke(obj, new Object[0]).toString(); // 绑定对象执行get函数
                        if (result == null)
                            return;
                        Class[] types2 = new Class[] { (new String())
                                .getClass() };// String 参数
                        Method setMeth = obj.getClass().getMethod(setName,
                                types2);
                        // setMeth.invoke(obj,
                        // new Object[] { new String(new String(result
                        // .getBytes("iso-8859-1"), "gbk")) }); // 绑定对象执行SET函数
                        setMeth.invoke(obj, new Object[] { java.net.URLDecoder
                                .decode(result, "UTF-8").toString().replaceAll(
                                        ",,..", "&") }); // 绑定对象执行SET函数
                    }
                }
            } catch (Exception e) {
                System.out.println("编码转换错误");
            }
        }
    }
}
